﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Xk
{
    public partial class frmSelectCourse : Form
    {
        DataSet ds = new DataSet();
        private int indexOfItemUnderMouseToDrag = -1;
        private int indexOfItemUnderMouseToDrop = -1;
        private int indexOfItemUnderMouseOver = -1;
        private Rectangle dragBoxFromMouseDown = Rectangle.Empty;

        public frmSelectCourse()
        {
            InitializeComponent();
        }

        private void getStuCou()
        {
            SqlConnection cn = new SqlConnection(Properties.Settings.Default.XkConnectionString);
            string sql = "SELECT StuCou.*,CouName FROM StuCou, Course";
            sql += " WHERE StuCou.CouNo=Course.CouNo AND StuNo=@StuNo";
            sql += " ORDER BY WillOrder";
            SqlDataAdapter da = new SqlDataAdapter(sql, cn);
            da.SelectCommand.Parameters.Add("StuNo", SqlDbType.NVarChar, 8).Value = CPublic.LoginInfo["StuNo"].ToString();
            cn.Open();
            da.Fill(ds, "StuCou");
            cn.Close();
            dgvSelectCourse.DataSource = ds.Tables["StuCou"];
        }

        private void getCourse()
        {
            SqlConnection cn = new SqlConnection(Properties.Settings.Default.XkConnectionString);
            string sql = "SELECT * FROM Course ORDER BY CouNo";
            SqlDataAdapter da = new SqlDataAdapter(sql, cn);
            try
            {
                cn.Open();
                da.Fill(ds, "Course");
            }
            catch (Exception ex)
            {
                MessageBox.Show("错误" + ex.Message, "错误信息", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                cn.Close();
            }
            dgvCourse.DataSource = ds.Tables["Course"];
        }

        private void frmSelectCourse_Load(object sender, EventArgs e)
        {
            dgvCourse.AutoGenerateColumns = false;
            dgvSelectCourse.AutoGenerateColumns = false;
            getStuCou();
            getCourse();
            CPublic.notSortDataGridView(dgvCourse);
        }

        private void SCourse()
        {
            if (dgvCourse.CurrentRow != null)
            {
                if (ds.Tables["StuCou"].Rows.Count < 5)
                {
                    string CouNo = dgvCourse.CurrentRow.Cells["CouNo"].Value.ToString();
                    DataRow[] adr;
                    adr = ds.Tables["StuCou"].Select("CouNo='" + CouNo + "'");
                    if (adr.Length == 0)
                    {
                        string CouName = dgvCourse.CurrentRow.Cells["CouName"].Value.ToString();
                        DataRow dr = ds.Tables["StuCou"].NewRow();
                        dr["CouNo"] = CouNo;
                        dr["CouName"] = CouName;
                        ds.Tables["StuCou"].Rows.Add(dr);
                    }
                    else
                    {
                        MessageBox.Show("该课程已报名，不要重复！", "选课", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    MessageBox.Show("已报名课程门数超过5门！", "选课", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            SCourse();
        }

        private void dgvCourse_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            SCourse();
        }

        private void CCourse()
        {
            if (dgvSelectCourse.CurrentRow != null)
            {
                int RowIndex = dgvSelectCourse.CurrentRow.Index;
                string CouNo = dgvSelectCourse.CurrentRow.Cells["SelectCouNo"].Value.ToString();
                DataRow[] adr;
                adr = ds.Tables["StuCou"].Select("CouNo='" + CouNo + "'");
                ds.Tables["StuCou"].Rows.Remove(adr[0]);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            CCourse();
        }

        private void dgvSelectCourse_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            CCourse();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            bool isSuccess = false;
            SqlConnection cn = new SqlConnection(Properties.Settings.Default.XkConnectionString);
            string sql = "DELETE FROM StuCou WHERE StuNo=@StuNo";
            SqlCommand cmd = new SqlCommand(sql, cn);
            cmd.Parameters.Add("StuNo", SqlDbType.NVarChar, 8).Value = CPublic.LoginInfo["StuNo"].ToString();
            cn.Open();
            cmd.ExecuteNonQuery();
            cn.Close();

            for (int i = 0; i < dgvSelectCourse.Rows.Count; i++)
            {
                sql = "INSERT StuCou(StuNo,CouNo,WillOrder,State) VALUES(@StuNo,@CouNO,@WillOrder,@State)";
                cmd = new SqlCommand(sql, cn);
                cmd.Parameters.Add("StuNo", SqlDbType.NVarChar, 8).Value = CPublic.LoginInfo["StuNo"].ToString();
                cmd.Parameters.Add("CouNo", SqlDbType.NVarChar, 8).Value = dgvSelectCourse.Rows[i].Cells["SelectCouNo"].Value;
                cmd.Parameters.Add("WillOrder", SqlDbType.SmallInt).Value = i + 1;
                cmd.Parameters.Add("State", SqlDbType.NVarChar, 2).Value = "报名";

                try
                {
                    cn.Open();
                    cmd.ExecuteNonQuery();
                    isSuccess = true;
                }
                catch
                {
                    isSuccess = false;
                }
                finally
                {
                    cn.Close();
                }
            }
            ds.Tables["StuCou"].Clear();
            getStuCou();
            if (isSuccess)
                MessageBox.Show("数据提交成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            else
                MessageBox.Show("数据提交失败", "错误信息", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void dgvSelectCourse_MouseDown(object sender, MouseEventArgs e)
        {
            DataGridView.HitTestInfo hitTest = dgvSelectCourse.HitTest(e.X, e.Y);
            
            if (hitTest.Type != DataGridViewHitTestType.Cell)
                return;

            indexOfItemUnderMouseToDrag = hitTest.RowIndex;

            if (indexOfItemUnderMouseToDrag > -1)
            {
                Size dragSize = SystemInformation.DragSize;
                dragBoxFromMouseDown = new Rectangle(new Point(e.X - (dragSize.Width / 2), e.Y - (dragSize.Height / 2)), dragSize);
            }
            else
            {
                dragBoxFromMouseDown = Rectangle.Empty;
            }
        }

        private void dgvSelectCourse_MouseUp(object sender, MouseEventArgs e)
        {
            dragBoxFromMouseDown = Rectangle.Empty;
        }

        private void OnRowDragOver(int rowIndex)
        {
            if (indexOfItemUnderMouseOver == rowIndex)
                return;

            int old = indexOfItemUnderMouseOver;
            indexOfItemUnderMouseOver = rowIndex;

            if (old > -1)
                dgvSelectCourse.InvalidateRow(old);

            if (rowIndex > -1)
                dgvSelectCourse.InvalidateRow(rowIndex);
        }

        private void dgvSelectCourse_MouseMove(object sender, MouseEventArgs e)
        {
            if ((e.Button & MouseButtons.Left) != MouseButtons.Left)
                return;

            if (dragBoxFromMouseDown == Rectangle.Empty || dragBoxFromMouseDown.Contains(e.X, e.Y))
                return;

            if (indexOfItemUnderMouseToDrag < 0)
                return;

            DataGridViewRow row = dgvSelectCourse.Rows[indexOfItemUnderMouseToDrag];
            DragDropEffects dropEffect = dgvSelectCourse.DoDragDrop(row, DragDropEffects.All);
            OnRowDragOver(-1);
        }

        private void dgvSelectCourse_DragOver(object sender, DragEventArgs e)
        {
            Point p = dgvSelectCourse.PointToClient(new Point(e.X, e.Y));

            DataGridView.HitTestInfo hitTest = dgvSelectCourse.HitTest(p.X, p.Y);

            if (hitTest.Type != DataGridViewHitTestType.Cell || hitTest.RowIndex == indexOfItemUnderMouseToDrag)
            {
                e.Effect = DragDropEffects.None;
                OnRowDragOver(-1);
                return;
            }
            e.Effect = DragDropEffects.Move;
            OnRowDragOver(hitTest.RowIndex);
        }

        private void dgvSelectCourse_DragDrop(object sender, DragEventArgs e)
        {
            Point p = dgvSelectCourse.PointToClient(new Point(e.X, e.Y));

            DataGridView.HitTestInfo hitTest = dgvSelectCourse.HitTest(p.X, p.Y);

            if (hitTest.Type != DataGridViewHitTestType.Cell || hitTest.RowIndex == indexOfItemUnderMouseToDrag + 1)
                return;

            indexOfItemUnderMouseToDrop = hitTest.RowIndex;

            DataRow tempRow = ds.Tables["StuCou"].NewRow();
            tempRow.ItemArray = ds.Tables["StuCou"].Rows[indexOfItemUnderMouseToDrag].ItemArray;
            ds.Tables["StuCou"].Rows.RemoveAt(indexOfItemUnderMouseToDrag);
            if (indexOfItemUnderMouseToDrag < indexOfItemUnderMouseToDrop)
                indexOfItemUnderMouseToDrop--;
            ds.Tables["StuCou"].Rows.InsertAt(tempRow, indexOfItemUnderMouseToDrop);
        }

        private void dgvSelectCourse_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            if (e.RowIndex == indexOfItemUnderMouseOver)
                e.Graphics.FillRectangle(Brushes.Red, e.RowBounds.X, e.RowBounds.Y, e.RowBounds.Width, 2);

            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
                e.RowBounds.Location.Y,
                dgvCourse.RowHeadersWidth - 4,
                e.RowBounds.Height);

            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
                dgvCourse.RowHeadersDefaultCellStyle.Font,
                rectangle,
                Color.Red,
                TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }
    }
}
